<?php

include_once("db.inc.php");
class DB
{
	private static $isPconnection 	= false;

	private static $usedConns 		= array(array());
	private static $usableConns 	= array(array());

	private static $arrConnConfig 	= array(array());

	public function DB()
	{
		global $ARR_GLOGAL_DB_CONFIG;
		
		DB::$arrConnConfig = $ARR_GLOGAL_DB_CONFIG;
	}

	public function getConnection($DBTag)
	{
		if(array_key_exists($DBTag, DB::$usableConns) && count(DB::$usableConns[$DBTag]) > 0){
			return array_pop(DB::$usableConns[$DBTag]);
		}else{
			return $this->newConnection($DBTag);
		}
	}

	public function newConnection($DBTag)
	{
		$db_connect 	= DB::$isPconnection ? 'mysql_pconnect' : 'mysql_connect'; 
		$conResource 	= $db_connect(DB::$arrConnConfig[$DBTag]["host"], DB::$arrConnConfig[$DBTag]["user"], DB::$arrConnConfig[$DBTag]["pwd"], true); 
		
		if($conResource){
			mysql_select_db(DB::$arrConnConfig[$DBTag]["db"], $conResource); 
			
			if(!empty(DB::$arrConnConfig[$DBTag]["encoding"])){
				$init_connect = "SET names " . DB::$arrConnConfig[$DBTag]["encoding"];
				mysql_query($init_connect, $conResource);
			}

			if(@mysql_error()) die('<b>error: connect database fail.</b> error : ' . mysql_error($conResource));

			if(array_key_exists($DBTag, DB::$usedConns)){
				$conns 		= DB::$usedConns[$DBTag];

				$conns[] 	= $conResource;
			}else{
				$conns 		= array();
				$conns[] 	= $conResource;
				
				DB::$usedConns[$DBTag] 	= $conns;
			}

			return $conResource;
		}else{
			return false;
		}
	}

	public function freeConnection($DBTag, $conn)
	{
		if(array_key_exists($DBTag, DB::$usedConns)){
			$conns = DB::$usedConns[$DBTag];

			if(in_array($conn, $conns)){
				if(array_key_exists($DBTag, DB::$usableConns)){
					$conns 		= DB::$usableConns[$DBTag];
	
					$conns[] 	= $conn;
					DB::$usableConns[$DBTag] = $conns;
				}else{
					$conns 		= array();
					$conns[] 	= $conn;
					
					DB::$usableConns[$DBTag] = $conns;
				}
			
				return true;
			}
		}else{ 
			return false;
		}
	}

	
}

?>
